package com.axend.aerosense.dev.viewmodel;

import android.app.Activity;

import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.bean.BaseStringBean;
import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.viewmodel.BaseViewModel;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.bean.RadarBean;
import com.axend.aerosense.common.bean.UnassignedRadar;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.ui.LoadingDialog;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.entity.DevRadarSettingBean;
import com.axend.aerosense.dev.entity.DevRadarSettingResBean;
import com.axend.aerosense.dev.entity.RadarNetworkBean;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.ProgressDialogCallBack;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.blankj.utilcode.util.ToastUtils;

import java.math.BigDecimal;

import io.reactivex.disposables.Disposable;

public class DevSettingViewModel extends CustomBaseViewModel<DevRadarSettingResBean> {

    private static final double START_HEIGHT = 140;
    private static final double END_HEIGHT = 220;
    private static final double START_WORK_DISTANCE = 300;
    private static final double END_WORK_DISTANCE = 700;

    private Disposable disposable;
    private RadarBean radarBean;
    String token;

    public MutableLiveData<Integer> bufferTime = new MutableLiveData<>(0);  //报警延时（s）（30-180s）
    public MutableLiveData<Integer> workDistance = new MutableLiveData<>(20);  //工作距离（m）(3-7m, 滑动条分为200份，步长2cm)
    public MutableLiveData<Integer> installHeight = new MutableLiveData<>(0);  //安装高度（1.40-2.2m 滑动条分为80份，每份1cm）

    public DevSettingViewModel(IBaseView baseViewImpl, ILoadDataResult<DevRadarSettingResBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
        token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
    }

    public void setRadarBean(RadarBean radarBean) {
        this.radarBean = radarBean;
    }

    @Override
    public void onLoad() {
        disposable = EasyHttp.post(UrlApi.URL.GetRadarSettings.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", token)
                .upJson(JsonUtil.toJson(new RadarNetworkBean(radarBean.getRadarUuid())))
                .execute(new SimpleCallBack<DevRadarSettingResBean>() {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        e.printStackTrace();
                        ToastUtils.showLong(e.getMessage());
                        loadDataFail(e.getMessage());
                    }

                    @Override
                    public void onSuccess(DevRadarSettingResBean bean) {
                        loadDataSuccess(bean);
                    }
                });
    }

    /**
     * 保存雷达参数
     */
    public void setSettings(Activity activity){
        DevRadarSettingBean devRadarSettingBean = new DevRadarSettingBean(
                getBufferTimeByInt(),
                getWorkDistanceByFloat(),
                getInstallHeightByFloat(),
                activity.getString(radarBean.getType().getName()),
                radarBean.getRadarUuid(),
                radarBean.getType().get());

        disposable = EasyHttp.post(UrlApi.URL.SetRadarSettings.getUrl())
                .cacheMode(CacheMode.NO_CACHE)
                .headers("token", token)
                .upJson(JsonUtil.toJson(devRadarSettingBean))
                .execute(new ProgressDialogCallBack<BaseStringBean>(LoadingDialog.getProgressDialog(activity)) {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        dismissProgress();
                        e.printStackTrace();
                        ToastUtils.showLong(e.getMessage());
                    }

                    @Override
                    public void onSuccess(BaseStringBean bean) {
                        dismissProgress();
                        ToastUtils.showLong(R.string.common_success);
                        activity.onBackPressed();
                    }
                });
    }

    public String getInstallHeightByString(MutableLiveData<Integer> height) {
        return ((height.getValue() + START_HEIGHT)/ 100) + " m";
    }

    //获取实际的安装高度（m）
    public float getInstallHeightByFloat() {
        double ft = (installHeight.getValue() + START_HEIGHT) / 100;
        BigDecimal bigDecimal = new BigDecimal(ft);
        float f2 = bigDecimal.setScale(4,   BigDecimal.ROUND_HALF_UP).floatValue();
        return (float) f2;
    }

    public String getWorkDistanceByString(MutableLiveData<Integer> distance){
        return ((distance.getValue() * 2 + START_WORK_DISTANCE) / 100) + " m";
    }

    //获取实际的工作距离（m）
    public float getWorkDistanceByFloat(){
        double m = (workDistance.getValue() * 2 + START_WORK_DISTANCE) / 100;
        BigDecimal bigDecimal = new BigDecimal(m);
        float f2 = bigDecimal.setScale(2,   BigDecimal.ROUND_HALF_UP).floatValue();
        return f2;
    }

    public String getBufferTimeByString(MutableLiveData<Integer> time){
        return (time.getValue() + 30) + " s";
    }

    //获取实际的报警延时（s）
    public int getBufferTimeByInt(){
        return bufferTime.getValue() + 30;
    }


    public void setInstallHeight(float f){
        double v = (f * 100 - START_HEIGHT);
        int progress = new BigDecimal(v).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        installHeight.setValue(progress);
    }

    public void setWorkDistance(float f){
        double v = (f * 100 - START_WORK_DISTANCE)  / 2;
        int progress = new BigDecimal(v).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        workDistance.setValue(progress);
    }

    public void setBufferTime(int value){
        bufferTime.setValue(value - 30);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (null != disposable){
            disposable.dispose();
        }
    }
}